<!DOCTYPE html>
<html lang="zh-cn">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>页面统计示例 - Analytics Demo</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      body {
        font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
        line-height: 1.6;
        color: #333;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        min-height: 100vh;
      }

      .container {
        max-width: 1200px;
        margin: 0 auto;
        padding: 20px;
      }

      .header {
        background: rgba(255, 255, 255, 0.95);
        padding: 30px;
        border-radius: 15px;
        margin-bottom: 30px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        text-align: center;
      }

      .header h1 {
        color: #2c3e50;
        margin-bottom: 10px;
        font-size: 2.5em;
      }

      .header p {
        color: #7f8c8d;
        font-size: 1.1em;
      }

      .stats-dashboard {
        background: rgba(255, 255, 255, 0.95);
        padding: 25px;
        border-radius: 15px;
        margin-bottom: 30px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
      }

      .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 20px;
        margin-bottom: 25px;
      }

      .stat-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 20px;
        border-radius: 10px;
        text-align: center;
        transition: transform 0.3s ease;
      }

      .stat-card:hover {
        transform: translateY(-5px);
      }

      .stat-value {
        font-size: 2em;
        font-weight: bold;
        margin-bottom: 5px;
      }

      .stat-label {
        font-size: 0.9em;
        opacity: 0.9;
      }

      .content-section {
        background: rgba(255, 255, 255, 0.95);
        padding: 30px;
        border-radius: 15px;
        margin-bottom: 30px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
      }

      .button-group {
        display: flex;
        flex-wrap: wrap;
        gap: 15px;
        margin: 20px 0;
      }

      .demo-button {
        padding: 12px 24px;
        border: none;
        border-radius: 25px;
        cursor: pointer;
        font-size: 16px;
        font-weight: 500;
        transition: all 0.3s ease;
        text-decoration: none;
        display: inline-block;
      }

      .btn-primary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
      }

      .btn-success {
        background: linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%);
        color: white;
      }

      .btn-warning {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        color: white;
      }

      .btn-info {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        color: white;
      }

      .demo-button:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
      }

      .form-section {
        margin: 25px 0;
      }

      .form-group {
        margin-bottom: 20px;
      }

      .form-group label {
        display: block;
        margin-bottom: 8px;
        font-weight: 500;
        color: #2c3e50;
      }

      .form-group input,
      .form-group textarea,
      .form-group select {
        width: 100%;
        padding: 12px;
        border: 2px solid #e0e0e0;
        border-radius: 8px;
        font-size: 16px;
        transition: border-color 0.3s ease;
      }

      .form-group input:focus,
      .form-group textarea:focus,
      .form-group select:focus {
        outline: none;
        border-color: #667eea;
      }

      .activity-log {
        background: #f8f9fa;
        border-radius: 10px;
        padding: 20px;
        max-height: 300px;
        overflow-y: auto;
      }

      .activity-item {
        padding: 8px 0;
        border-bottom: 1px solid #e0e0e0;
        font-size: 14px;
        color: #666;
      }

      .activity-item:last-child {
        border-bottom: none;
      }

      .timestamp {
        color: #999;
        font-size: 12px;
      }

      .footer {
        text-align: center;
        padding: 20px;
        color: rgba(255, 255, 255, 0.8);
      }

      @media (max-width: 768px) {
        .container {
          padding: 10px;
        }

        .header h1 {
          font-size: 2em;
        }

        .stats-grid {
          grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
        }

        .button-group {
          justify-content: center;
        }
      }
    </style>
  </head>
  <body>
    <div class="container">
      <!-- 页面头部 -->
      <div class="header">
        <h1>📊 页面统计示例</h1>
        <p>实时监控用户行为和页面数据</p>
      </div>

      <!-- 统计数据面板 -->
      <div class="stats-dashboard">
        <h2 style="margin-bottom: 20px; color: #2c3e50">📈 实时统计数据</h2>
        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-value" id="pageViews">1</div>
            <div class="stat-label">页面浏览量 (PV)</div>
          </div>
          <div class="stat-card">
            <div class="stat-value" id="stayTime">00:00</div>
            <div class="stat-label">页面停留时间</div>
          </div>
          <div class="stat-card">
            <div class="stat-value" id="clickCount">0</div>
            <div class="stat-label">总点击次数</div>
          </div>
          <div class="stat-card">
            <div class="stat-value" id="scrollDepth">0%</div>
            <div class="stat-label">页面滚动深度</div>
          </div>
          <div class="stat-card">
            <div class="stat-value" id="mouseMovements">0</div>
            <div class="stat-label">鼠标移动次数</div>
          </div>
          <div class="stat-card">
            <div class="stat-value" id="formInteractions">0</div>
            <div class="stat-label">表单交互次数</div>
          </div>
        </div>
      </div>

      <!-- 内容区域 -->
      <div class="content-section">
        <h2 style="margin-bottom: 20px; color: #2c3e50">🎯 交互测试区域</h2>

        <h3>按钮点击测试</h3>
        <div class="button-group">
          <button class="demo-button btn-primary" data-action="primary">主要按钮</button>
          <button class="demo-button btn-success" data-action="success">成功按钮</button>
          <button class="demo-button btn-warning" data-action="warning">警告按钮</button>
          <button class="demo-button btn-info" data-action="info">信息按钮</button>
          <a href="#section1" class="demo-button btn-primary" data-action="link">链接按钮</a>
        </div>

        <div class="form-section">
          <h3>表单交互测试</h3>
          <div class="form-group">
            <label for="username">用户名</label>
            <input type="text" id="username" name="username" placeholder="请输入用户名" />
          </div>
          <div class="form-group">
            <label for="email">邮箱</label>
            <input type="email" id="email" name="email" placeholder="请输入邮箱" />
          </div>
          <div class="form-group">
            <label for="category">分类</label>
            <select id="category" name="category">
              <option value="">请选择分类</option>
              <option value="tech">技术</option>
              <option value="design">设计</option>
              <option value="marketing">营销</option>
            </select>
          </div>
          <div class="form-group">
            <label for="message">留言</label>
            <textarea id="message" name="message" rows="4" placeholder="请输入您的留言"></textarea>
          </div>
          <button type="submit" class="demo-button btn-success" data-action="submit">
            提交表单
          </button>
        </div>
      </div>

      <!-- 活动日志 -->
      <div class="content-section">
        <h2 style="margin-bottom: 20px; color: #2c3e50">📝 用户行为日志</h2>
        <div class="activity-log" id="activityLog">
          <div class="activity-item">
            <span class="timestamp">[页面加载]</span>
            用户访问了页面
          </div>
        </div>
      </div>

      <!-- 更多内容用于测试滚动 -->
      <div class="content-section" id="section1">
        <h2>📖 更多内容区域</h2>
        <p>
          这里是一些示例内容，用于测试页面滚动深度统计。当用户滚动页面时，系统会自动记录滚动的深度百分比。
        </p>
        <p>
          页面统计是网站分析的重要组成部分，通过收集和分析用户行为数据，我们可以更好地了解用户需求，优化用户体验。
        </p>
        <p>常见的统计指标包括：页面浏览量(PV)、独立访客数(UV)、页面停留时间、跳出率、转化率等。</p>
      </div>

      <div class="content-section">
        <h2>🔧 技术实现</h2>
        <p>本示例使用纯JavaScript实现了以下统计功能：</p>
        <ul style="margin: 15px 0; padding-left: 30px">
          <li>页面浏览量统计</li>
          <li>用户停留时间计算</li>
          <li>点击事件追踪</li>
          <li>滚动深度监控</li>
          <li>鼠标移动统计</li>
          <li>表单交互记录</li>
          <li>用户行为日志</li>
        </ul>
      </div>

      <div class="footer">
        <p>© 2024 页面统计示例 - 实时监控用户行为数据</p>
      </div>
    </div>

    <script>
      // 统计数据对象
      const analytics = {
        pageViews: 1,
        startTime: Date.now(),
        clickCount: 0,
        mouseMovements: 0,
        formInteractions: 0,
        maxScrollDepth: 0,
        activities: []
      };

      // DOM 元素
      const elements = {
        pageViews: document.getElementById("pageViews"),
        stayTime: document.getElementById("stayTime"),
        clickCount: document.getElementById("clickCount"),
        scrollDepth: document.getElementById("scrollDepth"),
        mouseMovements: document.getElementById("mouseMovements"),
        formInteractions: document.getElementById("formInteractions"),
        activityLog: document.getElementById("activityLog")
      };

      // 格式化时间
      function formatTime(milliseconds) {
        const seconds = Math.floor(milliseconds / 1000);
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = seconds % 60;
        return `${minutes.toString().padStart(2, "0")}:${remainingSeconds
          .toString()
          .padStart(2, "0")}`;
      }

      // 添加活动日志
      function addActivity(message) {
        const timestamp = new Date().toLocaleTimeString();
        const activity = `[${timestamp}] ${message}`;
        analytics.activities.push(activity);

        const activityItem = document.createElement("div");
        activityItem.className = "activity-item";
        activityItem.innerHTML = `<span class="timestamp">[${timestamp}]</span> ${message}`;

        elements.activityLog.appendChild(activityItem);
        elements.activityLog.scrollTop = elements.activityLog.scrollHeight;

        // 限制日志条数
        if (elements.activityLog.children.length > 50) {
          elements.activityLog.removeChild(elements.activityLog.firstChild);
        }
      }

      // 更新统计显示
      function updateStats() {
        elements.pageViews.textContent = analytics.pageViews;
        elements.stayTime.textContent = formatTime(Date.now() - analytics.startTime);
        elements.clickCount.textContent = analytics.clickCount;
        elements.scrollDepth.textContent = analytics.maxScrollDepth + "%";
        elements.mouseMovements.textContent = analytics.mouseMovements;
        elements.formInteractions.textContent = analytics.formInteractions;
      }

      // 页面加载统计
      window.addEventListener("load", () => {
        addActivity("页面加载完成");
        updateStats();
      });

      // 点击事件统计
      document.addEventListener("click", e => {
        analytics.clickCount++;

        let elementInfo = e.target.tagName.toLowerCase();
        if (e.target.className) {
          elementInfo += "." + e.target.className.split(" ")[0];
        }
        if (e.target.id) {
          elementInfo += "#" + e.target.id;
        }

        const action = e.target.getAttribute("data-action") || "unknown";
        addActivity(`点击了 ${elementInfo} (${action})`);
        updateStats();
      });

      // 鼠标移动统计
      let mouseMoveThrottle = false;
      document.addEventListener("mousemove", e => {
        if (!mouseMoveThrottle) {
          analytics.mouseMovements++;
          mouseMoveThrottle = true;
          setTimeout(() => {
            mouseMoveThrottle = false;
            updateStats();
          }, 100); // 每100ms最多记录一次
        }
      });

      // 滚动深度统计
      let scrollThrottle = false;
      window.addEventListener("scroll", () => {
        if (!scrollThrottle) {
          scrollThrottle = true;
          setTimeout(() => {
            const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
            const documentHeight = document.documentElement.scrollHeight - window.innerHeight;
            const scrollDepth = Math.round((scrollTop / documentHeight) * 100);

            if (scrollDepth > analytics.maxScrollDepth) {
              analytics.maxScrollDepth = Math.min(scrollDepth, 100);
              addActivity(`页面滚动深度达到 ${analytics.maxScrollDepth}%`);
            }

            updateStats();
            scrollThrottle = false;
          }, 100);
        }
      });

      // 表单交互统计
      const formElements = document.querySelectorAll("input, textarea, select");
      formElements.forEach(element => {
        // 聚焦事件
        element.addEventListener("focus", e => {
          analytics.formInteractions++;
          addActivity(`聚焦到表单字段: ${e.target.name || e.target.id || e.target.tagName}`);
          updateStats();
        });

        // 输入事件
        let inputThrottle = false;
        element.addEventListener("input", e => {
          if (!inputThrottle) {
            analytics.formInteractions++;
            inputThrottle = true;
            setTimeout(() => {
              addActivity(`在 ${e.target.name || e.target.id || e.target.tagName} 中输入内容`);
              updateStats();
              inputThrottle = false;
            }, 500);
          }
        });

        // 选择事件
        element.addEventListener("change", e => {
          analytics.formInteractions++;
          addActivity(`修改了 ${e.target.name || e.target.id || e.target.tagName} 的值`);
          updateStats();
        });
      });

      // 页面可见性变化统计
      document.addEventListener("visibilitychange", () => {
        if (document.hidden) {
          addActivity("用户切换到其他标签页或最小化窗口");
        } else {
          addActivity("用户回到当前页面");
        }
      });

      // 页面离开统计
      window.addEventListener("beforeunload", e => {
        const stayTime = Date.now() - analytics.startTime;
        const stayTimeFormatted = formatTime(stayTime);

        // 发送统计数据到服务器（这里只是模拟）
        const statsData = {
          pageUrl: window.location.href,
          pageTitle: document.title,
          stayTime: stayTime,
          clickCount: analytics.clickCount,
          mouseMovements: analytics.mouseMovements,
          formInteractions: analytics.formInteractions,
          maxScrollDepth: analytics.maxScrollDepth,
          userAgent: navigator.userAgent,
          screenResolution: `${screen.width}x${screen.height}`,
          timestamp: new Date().toISOString(),
          activities: analytics.activities
        };

        // 使用 sendBeacon 确保数据能够发送
        if (navigator.sendBeacon) {
          navigator.sendBeacon("/api/analytics", JSON.stringify(statsData));
        }

        console.log("页面统计数据:", statsData);
      });

      // 定时更新停留时间
      setInterval(() => {
        updateStats();
      }, 1000);

      // 键盘事件统计
      document.addEventListener("keydown", e => {
        // 记录特殊按键
        const specialKeys = ["Enter", "Escape", "Tab", "Space"];
        if (specialKeys.includes(e.code.replace("Key", ""))) {
          addActivity(`按下了 ${e.code} 键`);
        }
      });

      // 窗口大小变化统计
      window.addEventListener("resize", () => {
        addActivity(`窗口大小变化为 ${window.innerWidth}x${window.innerHeight}`);
      });

      // 右键点击统计
      document.addEventListener("contextmenu", e => {
        addActivity("用户右键点击页面");
      });

      // 复制事件统计
      document.addEventListener("copy", () => {
        addActivity("用户复制了页面内容");
      });

      // 粘贴事件统计
      document.addEventListener("paste", () => {
        addActivity("用户粘贴了内容");
      });

      // 选择文本统计
      document.addEventListener("selectstart", () => {
        setTimeout(() => {
          const selection = window.getSelection().toString();
          if (selection.length > 0) {
            addActivity(
              `用户选择了文本: "${selection.substring(0, 50)}${selection.length > 50 ? "..." : ""}"`
            );
          }
        }, 100);
      });

      // 模拟发送数据到服务器的函数
      function sendAnalyticsData(eventType, data) {
        const payload = {
          eventType: eventType,
          timestamp: new Date().toISOString(),
          url: window.location.href,
          userAgent: navigator.userAgent,
          data: data
        };

        // 这里可以发送到实际的分析服务器
        console.log("发送统计数据:", payload);

        // 模拟 API 调用
        // fetch('/api/analytics', {
        //     method: 'POST',
        //     headers: {
        //         'Content-Type': 'application/json',
        //     },
        //     body: JSON.stringify(payload)
        // });
      }

      // 初始化统计
      addActivity("页面统计系统初始化完成");

      // 获取用户设备信息
      const deviceInfo = {
        userAgent: navigator.userAgent,
        language: navigator.language,
        platform: navigator.platform,
        screenResolution: `${screen.width}x${screen.height}`,
        windowSize: `${window.innerWidth}x${window.innerHeight}`,
        colorDepth: screen.colorDepth,
        timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
      };

      addActivity(`设备信息: ${deviceInfo.platform}, 分辨率: ${deviceInfo.screenResolution}`);
      console.log("用户设备信息:", deviceInfo);
    </script>
  </body>
</html>
